﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;

using Cognifide.PowerShell.Shell.Provider;

using Sitecore.Configuration;
using Sitecore.Data;
using System.Web;

namespace Cognifide.PowerShell.Shell.Commands
{
    public class BaseCommand : PSCmdlet
    {

        protected void RecoverHttpContext()
        {
            HttpContext.Current = this.SessionState.PSVariable.Get("HttpContext").Value as HttpContext;
        }

        protected bool IsCurrentDriveSitecore
        {
            get
            {
                return this.SessionState.Drive.Current.Provider.ImplementingType.IsSubclassOf(typeof(PsSitecoreItemProvider));
            }
        } 

        protected string CurrentDrive
        {
            get
            {
                return this.SessionState.Drive.Current.Name;
            }
        }

        protected Database CurrentDatabase
        {
            get
            {
                if (IsCurrentDriveSitecore)
                {
                    return Factory.GetDatabase(CurrentDrive);
                }
                else
                {
                    throw new InvalidPowerShellStateException("Current Sitecore database cannot be established, current location is not within a Sitecore content tree.");
                }
            }
        }

        protected string CurrentPath
        {
            get
            {
                return this.SessionState.Drive.Current.CurrentLocation;
            }
        }

        protected WildcardPattern GetWildcardPattern(string name)
        {
            if (String.IsNullOrEmpty(name))
            {
                name = "*";
            }
            WildcardOptions options = WildcardOptions.IgnoreCase | WildcardOptions.Compiled;
            WildcardPattern wildcard = new WildcardPattern(name, options);
            return wildcard;
        }

        protected void WildcardWrite<T>(string filter, IEnumerable<T> items, Func<T, string> propertyName)
        {
            WriteObject(WildcardFilter(filter, items, propertyName), true);
        }

        protected IEnumerable<T> WildcardFilter<T>(string filter, IEnumerable<T> items, Func<T, string> propertyName)
        {
            var wildcardPattern = GetWildcardPattern(filter);
            return items.Where(delegate(T item) { return wildcardPattern.IsMatch(propertyName(item)); });
        }

    }
}
